﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
using SFOOD.Common;

namespace SFOOD
{
    public class Cryto
    {
        private const string Key = "1i2u3y4g5h6j7v8b";
        //static readonly string SaltKey = "S@LT&KEY";
        private const string ViKey = "fedcba9876543210";

        //public static string Encrypt(string plainText)
        //{
        //    byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        //    byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
        //    var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
        //    var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));

        //    byte[] cipherTextBytes;

        //    using (var memoryStream = new MemoryStream())
        //    {
        //        using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
        //        {
        //            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
        //            cryptoStream.FlushFinalBlock();
        //            cipherTextBytes = memoryStream.ToArray();
        //            cryptoStream.Close();
        //        }
        //        memoryStream.Close();
        //    }
        //    return Convert.ToBase64String(cipherTextBytes);
        //}

        public static string Decrypt(string encryptedText)
        {
            var data = CryptographicBuffer.DecodeFromHexString(encryptedText);
            var keyBytes = CryptographicBuffer.ConvertStringToBinary(Key, BinaryStringEncoding.Utf8);
            var viKeyBytes = CryptographicBuffer.ConvertStringToBinary(ViKey, BinaryStringEncoding.Utf8);

            SymmetricKeyAlgorithmProvider aesProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbc);
            CryptographicKey aesKey = aesProvider.CreateSymmetricKey(keyBytes);
            var retun = CryptographicEngine.Decrypt(aesKey, data, viKeyBytes);
            return CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, retun).TrimEnd("\0".ToCharArray());
        }
    }
}
